package com.dataporter.gather.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.time.DateUtils;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dataporter.gather.patient.Patient;
import com.touchwisdom.modular.common.dao.HibernateDao;
import com.touchwisdom.modular.common.service.CommonService;

@Service
@Transactional
public class TemperatureService extends CommonService<Temperature, String> {
	@Resource
	private JdbcTemplate jdbcTemplate;

	@Resource
	private TemperatureDao temperatureDao;

	public Temperature findLatestByEquipNoAndMeasureTime(String equipNo, Date measureTime) {
		Query query = this.temperatureDao.createQuery("From Temperature Where equipNo=? and measureTime> ? order by measureTime desc", equipNo, measureTime);
		return (Temperature) query.setMaxResults(1).uniqueResult();
	}

	/**
	 * 查询体温信息
	 * 
	 * @param equipNo
	 *            设备号
	 * @param startTime
	 *            开始时时
	 * @param endTime
	 *            结束时间
	 */
	@SuppressWarnings("unchecked")
	public List<Temperature> query(final String equipNo, final Date startTime, final Date endTime, Integer rows) {
		if (rows == null) {
			rows = 20;
		}
		String sql = "FROM Temperature where equipNo=?";
		List<Object> argsList = new ArrayList<Object>();
		argsList.add(equipNo);
		if (startTime != null) {
			argsList.add(startTime);
			sql += " and measureTime>=?";
		}
		if (endTime != null) {
			Date endTimeInfo = new Date(endTime.getTime() + DateUtils.MILLIS_PER_DAY);
			argsList.add(endTimeInfo);
			sql += " and measureTime<?";
		}
		Query query = this.temperatureDao.createQuery(sql);
		int index = 0;
		for (Object obj : argsList) {
			query.setParameter(index++, obj);
		}
		query.setMaxResults(rows);
		return query.list();
	}

	/**
	 * 保存温度数据信息
	 * 
	 * @param temperature
	 */
	public void save(Temperature temperature) {
		// 如果存在相同时间的记录，那么执行更新，否则执行插入操作
		// final String equipNo = temperature.getEquipNo();
		// final Date timeInfo = temperature.getMeasureTime();
		// Temperature resultObj =
		// this.temperatureDao.findUnique("From Temperature where equipNo=? and measureTime=?",
		// equipNo, timeInfo);
		// if (resultObj != null) {
		// String objectId = resultObj.getId();
		// BeanUtils.copyProperties(temperature, resultObj);
		// resultObj.setId(objectId);
		// } else {
		// resultObj = temperature;
		// }
		super.saveEntity(temperature);
	}

	public Date getLatestDate(final Patient patient, final int distance) {
		// 查询最大的时间
		StringBuilder maxDateSql = new StringBuilder("SELECT max(measureTime) FROM Temperature where equipNo=?");
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(patient.getEquipNo());
		if (patient.getEndTime() != null) {
			maxDateSql.append(" and measureTime<=?");
			paramList.add(patient.getEndTime());
		}
		Query query = this.temperatureDao.createQuery(maxDateSql.toString());
		int index = 0;
		for (Object obj : paramList) {
			query.setParameter(index++, obj);
		}
		Date date = (Date) query.uniqueResult();
		return date;
	}

	static final String EXPORT_SQL = "SELECT measureNumOne,measureTime FROM T_Temperature where equipNo=? and measureTime>=DATE_SUB(?, INTERVAL ? DAY)";

	public List<Object> getLatestRecord(final Patient patient, final Date maxMeasureDate, final int distance) {
		List<Object> list = null;
		StringBuilder queryBuilder = new StringBuilder(EXPORT_SQL);
		List<Object> paramList = new ArrayList<Object>();
		paramList.add(patient.getEquipNo());
		paramList.add(maxMeasureDate);
		paramList.add(distance);
		if (patient.getEndTime() != null) {
			queryBuilder.append(" and measureTime<=?");
			paramList.add(patient.getEndTime());
		}
		SQLQuery resultQuery = this.temperatureDao.getSession().createSQLQuery(queryBuilder.toString());
		int index = 0;
		for (Object obj : paramList) {
			resultQuery.setParameter(index++, obj);
		}
		list = resultQuery.list();
		return list;
	}

	public Temperature getLatestPoint(final Date lastDate, final String equipNo) {
		Query query = this.getHibernateDao().createQuery("FROM Temperature where equipNo=? and measureTime>=? order by measureTime desc", equipNo, lastDate);
		Temperature temperature = (Temperature) query.setMaxResults(1).uniqueResult();
		return temperature;
	}

	@Override
	protected HibernateDao<Temperature, String> getHibernateDao() {
		return this.temperatureDao;
	}
}